<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
        <el-form-item label="证书编号" prop="certificateNo">
          <el-input
            v-model="queryParams.certificateNo"
            placeholder="请输入证书编号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter="handleQuery"
        />
        </el-form-item>
      <el-form-item label="批次号" prop="batchNo">
        <el-input
          v-model="queryParams.batchNo"
          placeholder="请输入批次号"
          clearable
          @keyup.enter="handleQuery"
        />
        </el-form-item>
        <el-form-item label="证书类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="请选择证书类型" clearable>
            <el-option
            v-if="dict.type && dict.type.certificate_type"
            v-for="dict in dict.type.certificate_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="certificateStatus">
          <el-select v-model="queryParams.certificateStatus" placeholder="请选择状态" clearable>
            <el-option label="已签发" value="已签发" />
            <el-option label="已作废" value="已作废" />
          <el-option label="有效" value="有效" />
          </el-select>
        </el-form-item>
        <el-form-item label="签发日期" prop="issueDateRange">
          <el-date-picker
            v-model="dateRange"
          size="small"
            style="width: 240px"
          value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Plus"
          @click="handleAdd"
        >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
          >删除</el-button>
        </el-col>
      <right-toolbar v-model:show-search="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="certificateList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="证书编号" align="center" prop="certificateNo" />
      <el-table-column label="产品名称" align="center" prop="productName" :show-overflow-tooltip="true" />
      <el-table-column label="批次号" align="center" prop="batchNo" />
        <el-table-column label="证书类型" align="center" prop="type">
          <template #default="scope">
          <dict-tag v-if="dict.type && dict.type.certificate_type" :options="dict.type.certificate_type" :value="scope.row.type"/>
          <span v-else>{{ scope.row.type }}</span>
          </template>
        </el-table-column>
      <el-table-column label="模板名称" align="center" prop="templateName" :show-overflow-tooltip="true" />
      <el-table-column label="签发日期" align="center" prop="issueDate" width="100">
          <template #default="scope">
          <span>{{ parseTime(scope.row.issueDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="签发人" align="center" prop="issuer" />
        <el-table-column label="状态" align="center" prop="certificateStatus">
          <template #default="scope">
          <el-tag :type="scope.row.certificateStatus === '有效' ? 'success' : (scope.row.certificateStatus === '已作废' ? 'danger' : 'info')">
              {{ scope.row.certificateStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button
              link
              icon="View"
              @click="handlePreview(scope.row)"
            >预览</el-button>
            <el-button
              link
            icon="Download"
            @click="handleDownload(scope.row)"
          >下载</el-button>
          <el-dropdown @command="(command) => handleCommand(command, scope.row)">
            <span class="el-dropdown-link">
              <el-button link>更多<el-icon><arrow-down /></el-icon></el-button>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="edit" icon="Edit" v-if="scope.row.certificateStatus !== '已作废'">编辑</el-dropdown-item>
                <el-dropdown-item command="void" icon="CircleClose" v-if="scope.row.certificateStatus !== '已作废'">作废</el-dropdown-item>
                <el-dropdown-item command="reissue" icon="Refresh" v-if="scope.row.certificateStatus === '已作废'">重新签发</el-dropdown-item>
                <el-dropdown-item command="print" icon="Printer">打印</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />

    <!-- 证书生成对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="模板选择" prop="templateId">
          <el-select v-model="form.templateId" placeholder="请选择证书模板" style="width: 100%" @change="handleTemplateChange">
            <el-option
              v-for="item in templateOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品选择" prop="productId">
          <el-select v-model="form.productId" placeholder="请选择产品" style="width: 100%" @change="handleProductChange">
            <el-option
              v-for="item in productOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="批次选择" prop="batchId">
          <el-select v-model="form.batchId" placeholder="请选择批次" style="width: 100%" @change="handleBatchChange">
            <el-option
              v-for="item in batchOptions"
              :key="item.id"
              :label="item.batchNo"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="证书类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择证书类型" style="width: 100%">
            <el-option
              v-if="dict.type && dict.type.certificate_type"
              v-for="dict in dict.type.certificate_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="签发日期" prop="issueDate">
          <el-date-picker
            v-model="form.issueDate"
            type="date"
            placeholder="选择签发日期"
            style="width: 100%"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="签发人" prop="issuer">
          <el-input v-model="form.issuer" placeholder="请输入签发人姓名" />
        </el-form-item>
        <el-form-item label="有效期至" prop="validUntil">
          <el-date-picker
            v-model="form.validUntil"
            type="date"
            placeholder="选择有效期"
            style="width: 100%"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="导出格式" prop="exportFormat">
          <el-radio-group v-model="form.exportFormat">
            <el-radio label="PDF">PDF</el-radio>
            <el-radio label="DOCX">Word文档</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
        <template #footer>
          <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
        </template>
      </el-dialog>

    <!-- 作废证书对话框 -->
    <el-dialog title="证书作废" v-model="voidDialogVisible" width="500px" append-to-body>
      <el-form ref="voidForm" :model="voidForm" :rules="voidRules" label-width="100px">
          <el-form-item label="证书编号">
          <el-input v-model="voidForm.certificateNo" disabled />
          </el-form-item>
        <el-form-item label="作废原因" prop="voidReason">
          <el-input
            v-model="voidForm.voidReason"
            type="textarea"
            placeholder="请输入作废原因"
            :rows="3"
          />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
          <el-button type="primary" @click="confirmVoid">确 定</el-button>
          <el-button @click="voidDialogVisible = false">取 消</el-button>
        </div>
        </template>
      </el-dialog>
  </div>
</template>

<script>
import { listCertificates, getCertificate, addCertificate, updateCertificate, deleteCertificate, downloadCertificate, voidCertificate } from "@/api/qep/certificate/certificate";
import { listTemplate } from '@/api/qep/certificate/template';
import { listProduct, getProduct } from '@/api/qep/product';
import { listBatches, getBatch } from '@/api/qep/production/batch';
import { ArrowDown, Search, Refresh, Plus, Edit, Delete, View, Download, CircleClose, Printer } from '@element-plus/icons-vue';
import { getDicts } from '@/api/system/dict/data';

export default {
  name: "CertificateManage",
  components: {
    ArrowDown,
    Search, 
    Refresh, 
    Plus, 
    Edit, 
    Delete, 
    View, 
    Download,
    CircleClose,
    Printer
  },
  dicts: ['certificate_type'],
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      certificateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        certificateNo: undefined,
        productName: undefined,
        batchNo: undefined,
        type: undefined,
        certificateStatus: undefined
      },
      // 表单参数
      form: {
        templateId: undefined,
        templateName: undefined,
        productId: undefined,
        productName: undefined,
        batchId: undefined,
        batchNo: undefined,
        type: undefined,
        issueDate: undefined,
        issuer: undefined,
        validUntil: undefined,
        exportFormat: "PDF",
        remark: undefined
      },
      // 表单校验
      rules: {
        templateId: [
          { required: true, message: "模板不能为空", trigger: "change" }
        ],
        productId: [
          { required: true, message: "产品不能为空", trigger: "change" }
        ],
        batchId: [
          { required: true, message: "批次不能为空", trigger: "change" }
        ],
        type: [
          { required: true, message: "证书类型不能为空", trigger: "change" }
        ],
        issueDate: [
          { required: true, message: "签发日期不能为空", trigger: "change" }
        ],
        issuer: [
          { required: true, message: "签发人不能为空", trigger: "blur" }
        ]
      },
      // 作废表单参数
      voidForm: {
        id: undefined,
        certificateNo: undefined,
        voidReason: undefined
      },
      // 作废表单校验
      voidRules: {
        voidReason: [
          { required: true, message: "作废原因不能为空", trigger: "blur" }
        ]
      },
      // 作废对话框
      voidDialogVisible: false,
      // 下拉选项
      templateOptions: [],
      productOptions: [],
      batchOptions: [],
      // 初始化字典对象
      dict: {
        type: {}
      }
    };
  },
  created() {
    try {
      console.log("正在初始化证书管理页面...");
      // 手动加载字典数据
      this.loadDictData();
      // 获取列表和选项数据
      this.getList();
      this.getTemplateOptions();
      this.getProductOptions();
    } catch (error) {
      console.error("初始化页面错误:", error);
      this.$message.error("初始化证书管理页面时遇到问题，请刷新页面重试");
    }
  },
  beforeDestroy() {
    // Clean up any DOM references or event listeners
    console.log("Certificate manage component is being destroyed");
  },
  errorCaptured(err, vm, info) {
    console.error(`Error captured in certificate component: ${err}, Info: ${info}`);
    // Return false to prevent the error from propagating further
    return false;
  },
  methods: {
    /**
     * 加载字典数据
     */
    loadDictData() {
      console.log("开始加载证书类型字典数据...");
      getDicts("certificate_type").then(response => {
        console.log("字典数据响应:", response);
        if (response && response.data) {
          const dictData = response.data.map(p => ({ 
            label: p.dictLabel, 
            value: p.dictValue, 
            elTagType: p.listClass, 
            cssClass: p.cssClass 
          }));
          
          // 设置字典数据 - 直接赋值而不是使用$set
          this.dict.type.certificate_type = dictData;
          console.log("字典数据加载成功:", dictData);
        } else {
          console.warn("字典API返回的数据为空");
          // 如果后端暂时没有数据，设置一些默认选项
          const defaultOptions = [
            { label: '质量证明书', value: 'quality_certificate', elTagType: 'info', cssClass: '' },
            { label: '合格证', value: 'conformity_certificate', elTagType: 'success', cssClass: '' },
            { label: '检验报告', value: 'inspection_report', elTagType: 'warning', cssClass: '' }
          ];
          this.dict.type.certificate_type = defaultOptions;
          console.log("使用默认字典数据:", defaultOptions);
        }
      }).catch(error => {
        console.error("加载字典数据失败:", error);
        // 设置默认选项防止页面出错
        const defaultOptions = [
          { label: '质量证明书', value: 'quality_certificate', elTagType: 'info', cssClass: '' },
          { label: '合格证', value: 'conformity_certificate', elTagType: 'success', cssClass: '' },
          { label: '检验报告', value: 'inspection_report', elTagType: 'warning', cssClass: '' }
        ];
        this.dict.type.certificate_type = defaultOptions;
        this.$message.warning("加载字典数据失败，已使用默认选项");
      });
    },
    
    /**
     * 确保字典数据已加载
     */
    ensureDictDataLoaded() {
      // 确保certificate_type字典数据已加载
      if (!this.dict.type.certificate_type) {
        this.loadDictData();
      }
    },
    /** 查询证书列表 */
    getList() {
      this.loading = true;
      try {
        listCertificates(this.addDateRange(this.queryParams, this.dateRange, 'issue')).then(response => {
          this.certificateList = response.rows;
          this.total = response.total;
          this.loading = false;
        }).catch(error => {
          console.error("Failed to get certificate list:", error);
          this.loading = false;
          this.$message.error("获取证书列表失败，请刷新页面重试");
        });
      } catch (error) {
        console.error("Error in getList:", error);
        this.loading = false;
        this.$message.error("获取证书列表时发生错误");
      }
    },
    /** 获取模板选项 */
    getTemplateOptions() {
      listTemplate({ pageSize: 100, status: "启用" }).then(response => {
        this.templateOptions = response.rows;
      });
    },
    /** 获取产品选项 */
    getProductOptions() {
      listProduct({ pageSize: 100 }).then(response => {
        this.productOptions = response.rows;
      });
    },
    /** 获取批次选项 */
    getBatchOptions(productId) {
      if (!productId) {
        this.batchOptions = [];
        return;
      }
      listBatches({ productId: productId, pageSize: 100 }).then(response => {
        this.batchOptions = response.rows;
      });
    },
    /** 表单重置 */
    reset() {
      this.form = {
        templateId: undefined,
        templateName: undefined,
        productId: undefined,
        productName: undefined,
        batchId: undefined,
        batchNo: undefined,
        type: undefined,
        issueDate: undefined,
        issuer: undefined,
        validUntil: undefined,
        exportFormat: "PDF",
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "生成证书";
    },
    /** 模板选择变更 */
    handleTemplateChange(value) {
      const template = this.templateOptions.find(item => item.id === value);
      if (template) {
        this.form.templateName = template.name;
        this.form.type = template.type;
      }
    },
    /** 产品选择变更 */
    handleProductChange(value) {
      this.form.batchId = undefined;
      this.form.batchNo = undefined;
      const product = this.productOptions.find(item => item.id === value);
      if (product) {
        this.form.productName = product.name;
      }
      this.getBatchOptions(value);
    },
    /** 批次选择变更 */
    handleBatchChange(value) {
      const batch = this.batchOptions.find(item => item.id === value);
      if (batch) {
        this.form.batchNo = batch.batchNo;
      }
    },
    /** 表单提交 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id) {
            // 修改
            updateCertificate(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
      });
    } else {
            // 生成新证书
            addCertificate(this.form).then(response => {
              this.$modal.msgSuccess("证书生成成功");
              this.open = false;
              this.getList();
              // 询问是否立即下载生成的证书
              this.$confirm('证书已生成，是否立即下载？', '提示', {
                confirmButtonText: '下载',
                cancelButtonText: '取消',
                type: 'info'
              }).then(() => {
                // 下载新生成的证书
                this.handleDownload(response.data);
              }).catch(() => {});
            });
          }
        }
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除证书编号为"' + ids + '"的数据项？').then(function() {
        return deleteCertificate(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 下拉菜单操作 */
    handleCommand(command, row) {
      switch (command) {
        case 'edit':
          this.handleEdit(row);
          break;
        case 'void':
          this.handleVoid(row);
          break;
        case 'reissue':
          this.handleReissue(row);
          break;
        case 'print':
          this.handlePrint(row);
          break;
        default:
          break;
      }
    },
    /** 预览证书 */
    handlePreview(row) {
      downloadCertificate(row.id).then(response => {
        // 如果是PDF则直接打开预览
        if (row.exportFormat === 'PDF') {
          const blob = new Blob([response], { type: 'application/pdf' });
          const url = window.URL.createObjectURL(blob);
          window.open(url);
        } else {
          // 否则直接下载
          const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
          const link = document.createElement('a');
          link.href = window.URL.createObjectURL(blob);
          link.download = row.certificateNo + '.docx';
          link.click();
          window.URL.revokeObjectURL(link.href);
        }
      });
    },
    /** 下载证书 */
    handleDownload(row) {
      downloadCertificate(row.id).then(response => {
        const contentType = row.exportFormat === 'PDF' 
          ? 'application/pdf' 
          : 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
        const fileExt = row.exportFormat === 'PDF' ? '.pdf' : '.docx';
        
        const blob = new Blob([response], { type: contentType });
        const link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = row.certificateNo + fileExt;
        link.click();
        window.URL.revokeObjectURL(link.href);
      });
    },
    /** 编辑证书 */
    handleEdit(row) {
      this.reset();
      getCertificate(row.id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改证书";
      });
    },
    /** 作废证书 */
    handleVoid(row) {
      this.voidForm.id = row.id;
      this.voidForm.certificateNo = row.certificateNo;
      this.voidForm.voidReason = '';
      this.voidDialogVisible = true;
    },
    /** 确认作废 */
    confirmVoid() {
      this.$refs["voidForm"].validate(valid => {
        if (valid) {
          voidCertificate(this.voidForm.id, this.voidForm.voidReason).then(response => {
            this.$modal.msgSuccess("证书已成功作废");
            this.voidDialogVisible = false;
            this.getList();
          });
        }
      });
    },
    /** 重新签发 */
    handleReissue(row) {
      this.reset();
      getCertificate(row.id).then(response => {
        const data = response.data;
        // 复制原证书信息，但移除ID和状态等
        this.form = {
          templateId: data.templateId,
          templateName: data.templateName,
          productId: data.productId,
          productName: data.productName,
          batchId: data.batchId,
          batchNo: data.batchNo,
          type: data.type,
          issueDate: this.parseTime(new Date(), '{y}-{m}-{d}'), // 使用当前日期
          issuer: data.issuer,
          validUntil: data.validUntil,
          exportFormat: data.exportFormat,
          remark: '（重新签发）' + (data.remark || '')
        };
        this.open = true;
        this.title = "重新签发证书";
      });
    },
    /** 打印证书 */
    handlePrint(row) {
      downloadCertificate(row.id).then(response => {
        // 对于PDF，打开新窗口并使用浏览器打印功能
        if (row.exportFormat === 'PDF') {
          const blob = new Blob([response], { type: 'application/pdf' });
          const url = window.URL.createObjectURL(blob);
          const printWindow = window.open(url);
          printWindow.onload = function() {
            printWindow.print();
          };
        } else {
          // 对于DOCX，只能下载后手动打印
          this.$modal.msgInfo("Word文档需要下载后使用Office软件打印");
          const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
          const link = document.createElement('a');
          link.href = window.URL.createObjectURL(blob);
          link.download = row.certificateNo + '.docx';
          link.click();
          window.URL.revokeObjectURL(link.href);
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
/* 样式保持不变 */
</style> 